﻿package com.calefk.util {
	
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.utils.getTimer;

    public class FPSCounter extends Sprite {
		
        private var last:uint = getTimer();
        private var updates:uint = 0;
        private var tf:TextField;

        public function FPSCounter(xPos:int = 0, yPos:int = 0, color:uint = 0x000000, 
				fillBackground:Boolean = true, backgroundColor:uint=0xffffff) {
            x = xPos;
            y = yPos;
            tf = new TextField();
            tf.textColor = color;
            tf.text = "----- fps";
            tf.selectable = false;
            tf.background = fillBackground;
            tf.backgroundColor = backgroundColor;
            tf.autoSize = TextFieldAutoSize.LEFT;
            addChild(tf);
            width = tf.textWidth;
            height = tf.textHeight;
            addEventListener(Event.ENTER_FRAME, update);
        }

        public function update(evt:Event):void {
            updates++;
            var now:uint = getTimer();
            var delta:uint = now - last;
            if (delta >= 1000) {
                var fps:Number = updates / delta * 1000;
                tf.text = fps.toFixed(1) + " fps";
                updates = 0;
                last = now;
            } 
        }
		
		public function clean():void {
			removeEventListener(Event.ENTER_FRAME , update);
			removeChild(tf);
			tf = null;
		}
    }
}